package com.demo.designmode.test;

import java.util.Random;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2022/5/17 17:12
 * @Version: 1.0
 */
public class Demo01 {

    public static void main(String[] args) {
        Employee employee = new Employee();
    }
}

class Employee {
    private static int nextId;

    private int id;
    private String name = "tom"; // 实例字段初始化
    private double salary;

    // 静态初始化块（只执行一次，且先于对象初始化之前执行）
    static {
        System.out.println("静态初始化块");
        Random generator = new Random();
        // set nextId to a random number between 0 and 9999
        nextId = generator.nextInt(10000);
    }

    // 对象初始化块（每次创建对象都执行一次）
    {
        System.out.println("对象初始化块");
        System.out.println("name = " + name); // 实例字段初始化优先于对象初始化之前执行
        id = nextId;
        nextId++;
    }

    // three overload constructor（在实例字段初始化、静态初始化块、对象初始化块之后执行）
    public Employee(String name, double salary) {
        System.out.println("构造器：Employee(String name, double salary)");
        this.name = name;
        this.salary = salary;
    }

    public Employee(double s) {
        // call the Employee(String name, double salary) constructor
        this("Employee #" + nextId, s);
        System.out.println("构造器：Employee(double s)");
    }

    // the default constructor
    public Employee() {
        System.out.println("构造器：Employee()");
        // name initialized to "" --see above
        // salary not explicitly set --initialized to 0
        // id initialized in initialization block
    }

    public double getId() {
        return id;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public void raiseSalary(double byPercent) {
        double raise = salary * byPercent / 100;
        salary += raise;
    }

    public String getName() {
        return name;
    }

    public boolean equals(Employee other) {
        // 类中的一个方法可以访问所有所属类的所有对象的私有数据
        return name.equals(other.name);
    }
}
